/********************************
* 3、编写一个算法，寻找并删除双向循环链表中元素值等于b的结点。
********************************/

#include<stdio.h>
#include<malloc.h>


struct NODE;
typedef struct NODE node;
struct NODE{int data;node* next,*prev;};

void print_circular(const node* p){
    int i = p->data;
    while(i--)printf("%d->",(p = p->next)->data);printf("\n");
}

void print_circular_reverse(const node* p){
    int i = p->data;
    p = p->next;
    while(i--)printf("%d<-",(p = p->prev)->data);printf("\n");
}

// append data and returns the address of the new node
node* append(node* h,int b){
    while(h->next)h=h->next;
    h->next = malloc(sizeof(node));
    h->next->prev = h;
    h = h->next;
    h->data = b;
    h->next = NULL;
    return h;
}

void list_remove(node* h,int b){
    node* p = h->next;
    node* q;
    while(h->data && p->next != h->next){
        if(p->next->data == b){
            q = p->next;
            p->next = q->next;
            q->next->prev = p;
            free(q);
            h->data--;
        }
        else p = p->next;
    }
    // in case head node's next needs to be removed 
    if(h->data && h->next->data == b){
        p = h->next;
        h->next = p->next;
        p->prev->next = p->next;
        p->next->prev = p->prev;
        free(p);
        h->data--;
    }
    if(h->data==0)h->next=NULL;
}


int main(){
    int n = 0,i,buf;
    node head;
    node* h = &head;
    h->prev = NULL;
    h->next = NULL;
    h->data = 0;

    node* p;

    scanf("%d",&n);
    for(i=0;i<n;i++){scanf("%d",&buf);p = append(h,buf);h->data++;}
    h->next->prev = p;
    p->next = h->next;
    printf("List: "); print_circular(h);

    printf("Remove: ");
    while(h->data&&scanf("%d",&buf)==1){
        list_remove(h,buf);
        printf("After removing %d: ",buf);print_circular(h);
    }

    while(h->next){p = h;h=h->next;free(p);}
    return 0;
}